package com.sddfp.trade.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.sddfp.client.access.TradeLogApi;
import com.sddfp.client.system.UserApi;
import com.sddfp.common.exception.BusinessException;
import com.sddfp.common.pojo.BankBidDTO;
import com.sddfp.common.pojo.BidBalanceDTO;
import com.sddfp.common.pojo.UserInfoVo;
import com.sddfp.common.result.Result;
import com.sddfp.common.result.enums.impl.BusinessCode;
import com.sddfp.common.result.enums.impl.ResultCode;
import com.sddfp.common.utils.CalculateExpectUtil;
import com.sddfp.common.utils.TokenUtils;
import com.sddfp.trade.entity.AgencyBid;
import com.sddfp.trade.entity.AgencyBidDTO;
import com.sddfp.trade.entity.AgencyBidVo;
import com.sddfp.trade.entity.BorrowRecord;
import com.sddfp.trade.mapper.AgencyBidMapper;
import com.sddfp.trade.mapper.BorrowRecordMapper;
import com.sddfp.trade.service.IAgencyBidService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @author yellow Docter
 * @date 2023 -03-04
 * @desc
 */
@Service
@Slf4j
public class AgencyBidServiceImpl extends ServiceImpl<AgencyBidMapper, AgencyBid>
        implements IAgencyBidService {

    @Autowired
    UserApi userApi;


    @Autowired
    BorrowRecordMapper borrowRecordMapper;

    @Autowired
    TradeLogApi tradeLogApi;

    @Override
    public AgencyBidVo addAgencyBidRecord(AgencyBidDTO agencyBidDTO) {
        Long userId = TokenUtils.getTokenUserId();
        Result<UserInfoVo> resultUser = userApi.findById(userId);
        UserInfoVo userInfoVo = resultUser.getData();
        String userCode = userInfoVo.getUserCode();

        // 访问托管代理服务，获取账户余额
        Result<BidBalanceDTO> resultBid = tradeLogApi.getBidBalance(userCode);
        BidBalanceDTO bidBalanceDTO = resultBid.getData();
        BigDecimal bidBalance = bidBalanceDTO.getBalance();

        // 投资金额与机构余额比较，判断账户是否充足
        BigDecimal amount = new BigDecimal(agencyBidDTO.getAmount());
        if (bidBalance.compareTo(amount) < 0) {
            throw new BusinessException(BusinessCode.BALANCE_NOT_ENOUGH);
        }

        BorrowRecord borrowRecord =
                borrowRecordMapper.selectById(agencyBidDTO.getBorrowRecordId());

        AgencyBid agencyBid = this.saveAgencyBid(userId, borrowRecord, amount,userInfoVo);

        //请求托管代理服务，发送认购数据
        BankBidDTO bankBidDTO = BankBidDTO.builder()
                .amount(amount) //冻结金额
                .bizType("BID") //业务类型
                .borrowRecordNo(borrowRecord.getBorrowRecordNo())
                .reqCode(borrowRecord.getReqCode())     //请求流水号
                .userCode(borrowRecord.getUserCode())   //用户编码
                .id(agencyBid.getId())  //业务实体标识
                .build();
        // 远程调用存管代理服务
        Result<String> resultBank =
                tradeLogApi.bankBidService(bankBidDTO);

        //根据结果更新认购状态
        if (resultBank.getCode() == ResultCode.SUCCESS.getCode()) {
            //3.2 修改状态为：已同步
            agencyBid.setStatus(1);
            this.updateById(agencyBid);
        }

        // 返回
        AgencyBidVo agencyBidVo = BeanUtil.copyProperties(agencyBid,AgencyBidVo.class);

        // 根据投资认购期限计算还款月数
        final Double ceil = Math.ceil(borrowRecord.getPeriod() / 30.0);
        Integer month = ceil.intValue();
        // 计算预期收益
        BigDecimal expected = CalculateExpectUtil.getIncomeTotalInterest(
                new BigDecimal(agencyBidDTO.getAmount()),
                new BigDecimal("0.5"), //TODO 年化收益
                month);
        agencyBidVo.setExpectedIncome(expected);
        return agencyBidVo;
    }

    // 保存投资认购记录
    private AgencyBid saveAgencyBid(Long userId,BorrowRecord borrowRecord,
                                    BigDecimal amount,UserInfoVo userInfoVo) {
        AgencyBid agencyBid = new AgencyBid();
        agencyBid.setUserId(userId);
        agencyBid.setName(userInfoVo.getUserName());
        agencyBid.setUserCode(userInfoVo.getUserCode());
        agencyBid.setAmount(amount);
        agencyBid.setBidStatus("FROZEN");
        agencyBid.setCreateDate(new Date());
        agencyBid.setReqCode(borrowRecord.getReqCode());
        agencyBid.setStatus(0);
        agencyBid.setBorrowRecordId(borrowRecord.getId());
        agencyBid.setBorrowRecordNo(borrowRecord.getBorrowRecordNo());
        agencyBid.setBorrowRecordName(borrowRecord.getName());
        agencyBid.setBorrowRecordPeriod(borrowRecord.getPeriod());
        agencyBid.setInvestRate(borrowRecord.getInvestRate());
        this.save(agencyBid);
        return agencyBid;
    }

}
